<template>
  <el-dialog
    v-model="dialogVisible"
    :align-center="true"
    title="充值"
    width="600px"
    @close="handleClose"
  >
    <el-scrollbar max-height="60vh">
      <el-form
        ref="ruleFormRef"
        label-width="auto"
        style="padding-right: var(--el-dialog-padding-primary)"
        :model="rechargeForm"
        :rules="rules"
      >
        <el-form-item label="货币类型" prop="currency" :rules="rules.currency">
          <el-select
            v-model="rechargeForm.currency"
            placeholder="请选择货币类型"
            clearable
            @change="handleCurrencyChange"
          >
            <el-option
              v-for="currency in currencyList"
              :key="currency"
              :label="currency"
              :value="currency"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="充值类型" prop="id" :rules="rules.id">
          <el-select
            v-model="rechargeForm.id"
            placeholder="请选择充值方式"
            clearable
          >
            <el-option
              v-for="pack in packageList"
              :key="pack.id"
              :label="pack.name"
              :value="pack.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="数量" prop="qty" :rules="rules.qty">
          <el-input v-model.number="rechargeForm.qty" />
        </el-form-item>
      </el-form>
    </el-scrollbar>
    <template #footer>
      <div style="padding-right: var(--el-dialog-padding-primary)">
        <el-button
          type="primary"
          v-bind:loading="loading"
          @click="handleSubmit(ruleFormRef)"
        >
          确 定
        </el-button>
        <el-button @click="handleClose">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import {
  type UploadUserFile,
  type FormRules,
  type FormInstance,
} from "element-plus";

import CreditAPI, { type PackageInfoVO } from "@/api/system/credit";
import router from "@/router";
import TransactionAPI, {
  type StripeCheckoutData,
  type StripeCheckoutResult,
} from "@/api/system/transaction";
import { loadStripe } from "@stripe/stripe-js";

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(["update:visible", "import-success"]);

const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => {
    emit("update:visible", val);
  },
});

const ruleFormRef = ref<FormInstance>();
const rechargeForm = reactive({
  qty: 1,
  id: "",
  currency: "",
});

const checkQty = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error("Please input the age"));
  }
  setTimeout(() => {
    if (!Number.isInteger(value)) {
      callback(new Error("Please input digits"));
    } else {
      if (value > 99) {
        callback(new Error("The quantity cannot exceed 99"));
      } else {
        callback();
      }
    }
  }, 100);
};

const rules = reactive<FormRules<typeof rechargeForm>>({
  id: [
    {
      required: true,
      message: "Please select",
      trigger: "blur",
    },
  ],
  currency: [
    {
      required: true,
      message: "Please select",
      trigger: "blur",
    },
  ],
  qty: [
    { validator: checkQty, trigger: "blur" },
    {
      required: true,
      message: "Please input",
      trigger: "blur",
    },
  ],
});

const handleClose = () => {
  dialogVisible.value = false;
};

const loading = ref(false);

const handleSubmit = (formEl: FormInstance | undefined) => {
  if (!formEl) {
    return;
  }
  loading.value = true;
  formEl.validate(async (valid) => {
    if (valid) {
      handleClose();

      loading.value = false;

      const tempCheckoutData: StripeCheckoutData = {
        id: Number(rechargeForm.id),
        quantity: rechargeForm.qty,
      };
      await TransactionAPI.checkout(tempCheckoutData).then(async (data) => {
        const { error } = stripe.value.redirectToCheckout({
          sessionId: data.sessionId,
        });
      });
    } else {
      console.log("error submit!");
      loading.value = false;
    }
  });
};

// 套餐列表
const packageList = ref<PackageInfoVO[]>([]);
const handleCurrencyChange = (currency: string) => {
  if (!rechargeForm.currency) {
    packageList.value = [];
    rechargeForm.id = "";
    rechargeForm.qty = 1;
    return;
  }
  CreditAPI.getPackageList(currency).then((data) => {
    if (!data || data.length == 0) {
      packageList.value = [];
      rechargeForm.id = "";
      rechargeForm.qty = 1;
    } else {
      packageList.value = data;
      rechargeForm.qty = 1;
    }
  });
};

const currencyList = ref<string[]>([]);
const getCurrencyList = () => {
  CreditAPI.getCurrencyList().then((data) => {
    currencyList.value = data;
  });
};

const stripe = ref();
onMounted(async () => {
  getCurrencyList();
  stripe.value = await loadStripe(
    `pk_test_51QGFzIPxAxRuNrv52NRrddAaDWgCRRmGz2uaOcWc5tR4U2jViyNmAaZbzBOiRArhYezV0yzWxzB6qcfZ5nWJiYh100z03WI8bf`
  );
});
</script>
